<template>
  <p-modal
    :title="handle === 'add'?'新增':'编辑'"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    :wrapClassName="'siteSourceModal'"
    @cancel="handleCancel"
  >
    <p-spin :spinning="confirmLoading">
      <p-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
      >
      <p-form-model-item label="资源类型" prop="resourceCode">
        <p-tree-select
          v-model="form.resourceCode"
          @change="treeChange"
          :replaceFields="replaceFields"
          style="width: 100%"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          :tree-data="selectTreeData"
          placeholder="请选择"
          :load-data="onLoadData"/>
      </p-form-model-item>
      <!-- <p-form-model-item label="资源名称" prop="resourceCode">
        <p-select @change="resourceCodeChange" placeholder="请选择" v-model="form.resourceCode">
          <p-select-option :title="item.name" :value="item.code" v-for="(item, index) in resourceCodeList" :key="item.code">
            {{item.name}}
          </p-select-option>
        </p-select>
      </p-form-model-item> -->
      <p-form-model-item label="资源规格型号" prop="resourceSpecification">
        <p-input
          placeholder="请输入内容"
          v-model="form.resourceSpecification"
        />
      </p-form-model-item>
      <p-form-model-item v-if="maintainContentCodeList.length>0" label="点检内容" prop="maintainContentCode">
        <p-select v-model="form.maintainContentCode" @change="maintainContentCodeChange">
          <p-select-option 
            :value="item.code"
            v-for="(item, index) in maintainContentCodeList" 
            :key="item.code">
            {{item.name}}
          </p-select-option>
        </p-select>
      </p-form-model-item>
      <p-form-model-item v-if="maintainContentCodeList.length>0" label="点检标准" prop="maintainStandard">
        <p-input
          placeholder="请输入内容"
          v-model="form.maintainStandard"
        />
      </p-form-model-item>
      <p-form-model-item v-if="maintainContentCodeList.length>0" label="标准上限" prop="maintainLimit">
        <p-input
          placeholder="请输入内容"
          v-model="form.maintainLimit"
        />
      </p-form-model-item>
      <p-form-model-item v-if="maintainContentCodeList.length>0" label="点检下限" prop="maintainFloor">
        <p-input
          placeholder="请输入内容"
          v-model="form.maintainFloor"
        />
      </p-form-model-item>
      <p-form-model-item label="数量" prop="quantity">
        <p-input
          placeholder="请输入内容"
          v-model="form.quantity"
        />
      </p-form-model-item>
    </p-form-model>
    </p-spin>
  </p-modal>
</template>

<script>
import _ from "lodash";
import mesPeProcess from "@/api/mesPeProcess";
export default {
  name: "siteSourceModal",
  components: {
  },
  data() {
    return {
      handle: '',
      width: 500,
      visible: false,
      model: {},
      confirmLoading: false,
      replaceFields: {
        children:'children',
        title:'name', 
        value:'code',
        key:'id',
      },
      selectTreeData: [],
      resourceCodeList: [
        /* {
          name: 'label',
          code: 'label',
        }, */
      ],
      maintainContentCodeList:[
        /* {
          name: 'label',
          code: 'label',
        }, */
      ],
      form: {
        resourceCode: '', // 资源编码
        resourceCodeCopy: '', // 资源编码copy
        resourceCodeTag: false, // 为true表示回显，并且树的数据中没有该 resourceCode，此时直接展示其名称
        resourceName: '', // 资源名称
        resourceTypeCode: '',
        resourceTypeName: '',
        resourceSpecification: '',
        maintainContentCode: '',
        maintainContentName: '',
        maintainStandard: '',
        maintainLimit: '',
        maintainFloor: '',
        quantity: 1,
      },
      rules: {
        resourceCode: [
          { required: true, message: '请选择', trigger: 'change' },
        ],
        resourceTypeCode: [
          { required: true, message: '请选择', trigger: 'change' },
        ],
        resourceSpecification: [
          { required: true, message: '请输内容', trigger: 'blur' },
        ],
        maintainContentCode: [
          { required: true, message: '请选择', trigger: 'change' },
        ],
        maintainStandard: [
          { required: true, message: '请输内容', trigger: 'blur' },
        ],
        maintainLimit: [
          { required: true, message: '请输内容', trigger: 'blur' },
        ],
        maintainFloor: [
          { required: true, message: '请输内容', trigger: 'blur' },
        ],
        quantity: [
          {  required: true, validator: this.validateQuantity, trigger: 'blur' },
        ],
      },
    };
  },
  watch: {
    visible(){
      if (this.handle === 'edit'){
        /* if (this.resourceCodeList.length === 0){
          this.getEquipments();
        } */
        if (this.maintainContentCodeList.length === 0){
          this.getTemplatelist();
        }
      }
    },
  },
  created() {
    this.getEquipmentTypeNode();
  },
  methods: {
    validateQuantity(rule, value, callback){
      if (value === '' || value === null) {
        callback(new Error('请输入内容'));
      } else if (!(/^[1-9]\d*$/.test(value))) {
        callback(new Error("只能输入正整数"));
      } else {
        callback();
      } 
    },
    handleOk(){
      const that = this;
      that.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (this.form.resourceCodeTag){
            that.form.resourceCode = that.form.resourceCodeCopy;
          }
          if ( that.handle === 'add' ){
            that.form.id = new Date().getTime();
            if (this.maintainContentCodeList.length === 0){
              that.form.maintainStandard = '';
              that.form.maintainLimit = '';
              that.form.maintainFloor = '';
            }
            that.$parent.options.push(_.cloneDeep(that.form));
          }else {
            if (this.maintainContentCodeList.length === 0){
              that.form.maintainStandard = '';
              that.form.maintainLimit = '';
              that.form.maintainFloor = '';
            }
            const index = that.$parent.options.findIndex( el => el.id === that.form.id);
            that.$parent.options.splice(index,1,_.cloneDeep(that.form))
          }
          that.$parent.optionsCopy = _.cloneDeep(that.$parent.options);
          that.visible = false;
        }
      });
    },
    handleCancel(){
      this.visible = false;
      this.$refs.ruleForm.resetFields();
    },
    getEquipments(categoryId){
      mesPeProcess.getEquipments({categoryId,}).then( res =>{
        if (res.code === 0){
          this.resourceCodeList = res.data || [];
        }
      })
    },
    treeChange(value, label, extra){
      // 名称
      this.form.resourceName = label[0];
      // 类型
      this.form.resourceTypeCode = extra.triggerNode.$parent.value;
      this.form.resourceTypeName = extra.triggerNode.$parent.title;
      this.form.resourceCodeTag = false;
      // this.getEquipments(extra.triggerNode.eventKey);
      this.getTemplatelist();
    },
    onLoadData(treeNode){
      const { id } = treeNode.dataRef;
      const _this = this;
      return new Promise((resolve) => {
        if (treeNode.dataRef.children) { // 有值了直接渲染
          resolve()
          return
        }
        // 没有值根据当前父节点获取下面子节点并挂在树节点中，添加到对应父节点的children中
        mesPeProcess.getEquipmentTypeNode({parentId: id}).then( res =>{
          if (res.code === 0){
            const curData = res.data || [];
            curData.forEach( el =>{
              if (!el.isLeaf){
                el.disabled = true;
              }
              if (this.form.resourceCodeTag && el.code === this.form.resourceCodeCopy){
                this.form.resourceCode = this.form.resourceCodeCopy;
                this.form.resourceCodeTag = false;
              }
            });
            treeNode.dataRef.children = curData;
            _this.selectTreeData = [..._this.selectTreeData]
          }
        })
        resolve()
      })
    },
    getEquipmentTypeNode(){
      mesPeProcess.getEquipmentTypeNode({parentId: 0}).then( res =>{
        if (res.code === 0){
          const curData = res.data || [];
          curData.forEach( el =>{
            if (!el.isLeaf){
              el.disabled = true;
            }
          });
          this.selectTreeData = curData;
        }
      })
    },
    /* resourceCodeChange(val){
      this.form.resourceName = this.resourceCodeList.find( el => el.code === val ).name;
      this.getTemplatelist();
    }, */
    maintainContentCodeChange(val){
      this.form.maintainContentName = this.maintainContentCodeList.find( el => el.code === val ).name;
    },
    getTemplatelist(){
      mesPeProcess.getTemplatelist({
        equno: this.form.resourceCode,
        standard: 'GZZYSX',
      }).then( res =>{
        if (res.code === 0){
          const curData = res.data || [];
          this.maintainContentCodeList = curData.map( el => {
            return {
              code: el.checkno,
              name: el.position,
            }
          });
        }
      })
    },
  },
};
</script>

<style lang="less">
  .siteSourceModal {
    .poros-form .poros-form-item{
      display: flex;
    }
    .poros-form-item-label{
      width: 110px;
    }
    .poros-form-item .poros-form-item-control-wrapper{
      overflow: hidden;
    }
  }
</style>

